using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.IO.Compression;
using System.Text;
using System.Web;
using System.Xml;

/// <summary>
/// Summary description for CSSModule
/// </summary>
/// 
namespace FlickrXplorer.Web
{
    public class CssHandler : IHttpHandler
    {

        private static readonly IDictionary<string, string> cssMapping = LoadMaps();

        private static IDictionary<string, string> LoadMaps()
        {

            using (TextReader reader = new StreamReader(System.AppDomain.CurrentDomain.BaseDirectory + "\\CssMappings.xml"))
            {
                IDictionary<string, string> dic = new Dictionary<string, string>();

                XmlReaderSettings readerSetting = new XmlReaderSettings();

                readerSetting.IgnoreComments = true;
                readerSetting.IgnoreProcessingInstructions = true;
                readerSetting.IgnoreWhitespace = true;

                XmlReader xmlReader = XmlReader.Create(reader, readerSetting);

                while (xmlReader.Read())
                {
                    string key = string.Empty;
                    string value = string.Empty;

                    if (xmlReader.MoveToAttribute("browser"))
                    {
                        key = xmlReader.Value.ToLower();
                    }

                    string css = string.Empty;

                    if (xmlReader.MoveToAttribute("file"))
                    {
                        string file = xmlReader.Value;
                        if (file.Length > 0)
                        {
                            string[] fileNames = file.Split('|');
                            foreach (string fileName in fileNames)
                            {
                                value = System.AppDomain.CurrentDomain.BaseDirectory + fileName;

                                TextReader configPath = new StreamReader(value);
                                string content = configPath.ReadToEnd();
                                configPath.Close();

                                content = content.Replace("\r\n", string.Empty)
                                              .Replace("\t", string.Empty);

                                content = System.Text.RegularExpressions.Regex.Replace(content, @"/\*[^/]*/", string.Empty);

                                css += content;
                            }
                        }
                    }

                    if (key.Length > 0 && css.Length > 0)
                    {
                        dic.Add(key, css);
                    }
                }
                return dic;
            }
        }


        #region IHttpHandler Members

        public bool IsReusable
        {
            get { return false; }
        }

        public void ProcessRequest(HttpContext context)
        {
            string content = string.Empty;
            StringBuilder builder = new StringBuilder();
            HttpBrowserCapabilities browser = context.Request.Browser;

            foreach (string key in cssMapping.Keys)
            {
                if (string.Compare(key, "all", true) == 0)
                {
                    builder.Append(cssMapping[key]);
                }
                else if (key.Substring(key.Length - 1, 1) == "*")
                {
                    string newKey = key.Substring(0, key.Length - 1);

                    if (string.Compare(newKey, browser.Browser, true) == 0)
                    {
                        builder.Append(cssMapping[key]);
                    }
                }
                else if (string.Compare(key, browser.Browser + browser.MajorVersion.ToString(), true) == 0)
                {
                    builder.Append(cssMapping[key]);
                }
            }
            // compression 
            string acceptEncoding = context.Request.Headers["Accept-Encoding"];

            if (!string.IsNullOrEmpty(acceptEncoding))
            {
                acceptEncoding = acceptEncoding.ToLower(CultureInfo.InvariantCulture);
            }

            if (acceptEncoding.Contains("gzip"))
            {
                context.Response.Filter = new GZipStream(context.Response.Filter, CompressionMode.Compress);
                context.Response.AddHeader("Content-encoding", "gzip");
            }

            context.Response.ContentType = "text/css";
            context.Response.ContentEncoding = System.Text.Encoding.UTF8;

            context.Response.Cache.SetCacheability(HttpCacheability.Public);
            context.Response.Cache.SetExpires(DateTime.Now.AddDays(30));

            string fullContent = builder.ToString();

            string appPath = VirtualPathUtility.RemoveTrailingSlash(context.Request.ApplicationPath);
            
            if (appPath != "/")
            {
                fullContent = fullContent.Replace("__APPPATH__", appPath + "/");
            }
            else
            {
                fullContent = fullContent.Replace("__APPPATH__","/");
            }

            context.Response.Write(fullContent);
            context.Response.End();
        }

        #endregion

    }
}
